<?php
namespace app\index\service;
use think\Db;
use app\index\model\Type;
use app\index\model\SubUser;
use app\index\model\KnowUserLog;
use app\index\model\SubUserInfo;
use app\index\model\SubQuestion;
use app\index\model\SubTestpaper;


class SubService
{
	public function createTestPaper($param)
	{
		$initialQuesIds = SubQuestion::getTypeDataQuesIds([$param['s_id']], 's_id');

		if (!$initialQuesIds) return [];

		if(count($initialQuesIds) > $param['points'])
		{
			$quesRandIds = array_rand($initialQuesIds,$param['points']);

			foreach($quesRandIds as $v)
			{
				$quesIds[] = $initialQuesIds[$v];
			}
		}
		else
		{
			$quesIds = $initialQuesIds;
		}

		shuffle($quesIds);

		$tId = SubTestpaper::createPaper(['quesIds'=>$quesIds, 'course_id'=> $param['course_id'], 'meta_id'=>$param['s_id'],'meta_name'=>'s_id']);

		return [$tId, $quesIds];
	}


	public function getQuestions($course, $param, $field = 's_id')
	{
		$papers = SubTestpaper::getOneData([$field => $param[$field],'course_id' => $course['course_id'],'status' => 0], $field);

		$tId = $papers['id'];

		$quesIds = $papers ? explode(',', $papers['ques_id']) : '';

		if ( !$papers )
		{
			list($tId, $quesIds) = self::createTestPaper($course);

			$logs = KnowUserLog::getUserDataOne(['id'=>$course['course_id']]);

			if (!$logs) KnowUserLog::addData([
				'id' => $course['course_id'],
				'points' => 0,
				'origin_points' => $course['points'],
			]);
		}

		$userQues = SubUser::getTestQuesIds($tId, $quesIds);

		if ($param['sort'])
		{
			$sort = $param['sort'];
		}
		else
		{
			$sort = 1;

			if ($userQues)

				foreach ($quesIds as $key => $id)
				{
					if ($userQues[$id] == 1)
					{
						$sort++;
					}
					else
					{
						break;
					}
				}
		}

		/*if ($sort > count($quesIds))
		{
			SubTestpaper::where('id',$tId)->update(['status'=>1]);

			list($tId, $quesIds) = self::createTestPaper($course);

			$userQues = SubUser::getTestQuesIds($tId, $quesIds);

			$sort = 1;
		}*/

		$data = SubQuestion::getQuesOne($quesIds[$sort-1]);

		return [ $data, $quesIds, $tId, $userQues, $sort];
	}
}